package model

import (
	"awesomeProject2/global"
	"gorm.io/gorm"
	"strconv"
)

type Work struct {
	gorm.Model
	NumberOfWords float64 `json:"numberOfWords" gorm:"type:float"`
	PubName       string  `json:"pubName"  gorm:"type:varchar(255)"`
	PubTime       string  `json:"pubTime" gorm:"type:varchar(255)"`
	WorkCategory  string  `json:"workCategory"  gorm:"type:varchar(255)"`
	WorkFile      string  `json:"workFile"  gorm:"type:varchar(255)"`
	WorkLevel     string  `json:"workLevel"  gorm:"type:varchar(255)"`
	WorkName      string  `json:"workName"  gorm:"type:varchar(255)"`
	WorkRanking   int     `json:"workRanking"  gorm:"type:int"`
	UserId        uint    `json:"userid"  gorm:"type:bigint"`
	IsVisible     bool    `json:"is_visible" gorm:"type:tinyint"`
	Year          int     `json:"year" gorm:"type:int"`
}

func GetWork(id uint) (err error, work Work) {
	err = global.GVA_DB.Where("id = ?", id).First(&work).Error
	return err, work
}

func CreateWork(work Work) (err error) {
	err = global.GVA_DB.Create(&work).Error
	return err
}
func DeleteWork(id int) (err error) {
	err = global.GVA_DB.Where("id = ?", id).Delete(&Work{}).Error
	return err
}

func UpdateWork(work Work) (err error) {
	err = global.GVA_DB.Updates(&work).Where("id = ?", work.ID).Error
	return err
}

func GetWorks(userid uint, pageSize int, pageNum int) (err error, list interface{}, total int) {
	var works []Work
	var tt int64
	err = global.GVA_DB.Limit(pageSize).Offset((pageNum-1)*pageSize).Where("uerid = ?", userid).Find(&works).Count(&tt).Error

	tmp := strconv.FormatInt(tt, 10)
	total, _ = strconv.Atoi(tmp)
	return err, works, total
}
func ChangeWorkVisiblity(id uint) (err error) {
	var data Work
	err = global.GVA_DB.Where("id = ?", id).First(&data).Error
	data.IsVisible = !data.IsVisible
	global.GVA_DB.Updates(data)
	return err
}
func GetAllWorks(id uint, year int) (error, interface{}, int64) {
	var data []Work
	var tt int64
	err := global.GVA_DB.Where("user_id = ? AND year = ?", id, year).Find(&data).Count(&tt).Error
	return err, data, tt
}

func GetAllWorks3(id uint) (error, interface{}, int64) {
	var data []Work
	var tt int64
	err := global.GVA_DB.Where("user_id = ? ", id).Find(&data).Count(&tt).Error
	return err, data, tt
}

//统计总数目
func GetAllwk(year int) (error, int64) {
	var tt int64
	err := global.GVA_DB.Model(&Work{}).Where("year = ?", year).Count(&tt).Error
	return err, tt
}
